#!/bin/bash
set -e

PLATFORM="$(uname -s | tr '[:upper:]' '[:lower:]')"
KUBERNETES_VERSION=__KUBERNETES_VERSION__
KUB_URL="https://storage.googleapis.com/kubernetes-release/release/v${KUBERNETES_VERSION}/bin/${PLATFORM}/amd64/kubectl"

scream () {
    cat <<< "$@" 1>&2
    exit 1
}

case "$PLATFORM" in
  darwin|linux)
    targetDir="/usr/local/bin"
    if [[ -r /etc/os-release ]]; then
      . /etc/os-release
      if [[ $ID = coreos ]]; then
        targetDir="/opt/bin"
        unlink $HOME/.bash_profile
        cp /usr/share/skel/.bash_profile $HOME/.bash_profile
        chmod 775 $HOME/.bash_profile
      fi
    fi
    ;;
  *)
    scream "Unknown or unsupported platform: ${PLATFORM}"
    ;;
esac

if [[ "$#" -eq 1 && "$1" == "install"  ]] ; then
  doinstall="true"
  if [ -x ${targetDir}/kubectl ]; then
    installedversion=`${targetDir}/kubectl version | awk -F":" '{print $5}' | head -n1 | awk -F"," {'print $1'} | tr -d "\"" | tr -d "v"`
    if [ "$installedversion" == "${KUBERNETES_VERSION}" ]; then
      echo "kubectl already installed in version '$installedversion'. Skipping install."
      doinstall="false"
    else
      echo "kubectl installed in version '$installedversion' instead of '${KUBERNETES_VERSION}'. Reinstalling."
    fi
  fi

  if [ "$doinstall" == "true" ]; then 
    echo "Downloading and installing ${PLATFORM} version of 'kubectl' v${KUBERNETES_VERSION} into ${targetDir}. This may take a couple minutes, depending on your internet speed.."
    [ -d ${targetDir} ] || sudo mkdir -p ${targetDir}
    sudo -E curl -s -k -L -o ${targetDir}/kubectl "${KUB_URL}"
    [ -x ${targetDir}/kubectl ] || sudo chmod +x ${targetDir}/kubectl
  fi

  # use sed to replace current values, if any; create profile file if not exists
  touch -a $HOME/.bash_profile
  echo "Configuring environment.."
  __PROXY_LINE__if ! grep -q 'export NO_PROXY' $HOME/.bash_profile ; then
  __PROXY_LINE__  echo "export NO_PROXY=__NO_PROXY__" >> $HOME/.bash_profile
  __PROXY_LINE__  echo "export no_proxy=__NO_PROXY__" >> $HOME/.bash_profile
  __PROXY_LINE__else
  __PROXY_LINE__  sed -i'*' 's|.*export NO_PROXY.*|export NO_PROXY=__NO_PROXY__|' $HOME/.bash_profile
  __PROXY_LINE__  sed -i'*' 's|.*export no_proxy.*|export no_proxy=__NO_PROXY__|' $HOME/.bash_profile
  __PROXY_LINE__fi
  __PROXY_LINE__export NO_PROXY=__NO_PROXY__
  __PROXY_LINE__export no_proxy=__NO_PROXY__
elif [[ "$#" -eq 1 && "$1" == "uninstall"  ]] ; then
  echo "Removing 'kubectl' v${KUBERNETES_VERSION}.."
  [ -f ${targetDir}/kubectl ] && sudo rm -f ${targetDir}/kubectl
else
  echo "Usage: ./setup (install|uninstall)"
fi
